package com.tgu.home_action.service.impl;

import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.facebody.model.v20191230.SearchFaceResponse;
import com.tgu.home_action.dao.*;
import com.tgu.home_action.pojo.*;
import com.tgu.home_action.pojo.state.RabbitMq;
import com.tgu.home_action.pojo.state.ResponseState;
import com.tgu.home_action.service.FaceService;
import com.tgu.home_action.service.utils.AliYunService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

@Service
public class FaceServiceImpl implements FaceService {
    @Autowired
    private ClientMapper clientMapper;
    @Autowired
    private FaceMapper faceMapper;
    @Autowired
    private OldManMapper oldManMapper;
    @Autowired
    private AliYunService aliYunService;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private CaseMapper caseMapper;
    @Autowired
    private VolunteerMapper volunteerMapper;
    @Autowired
    private VolunteerInformationMapper volunteerInformationMapper;

    /**
     * 人脸识别
     */
    @Override
    public ResponseData<Face> faceIdentification(@NotNull(message = "imgUrl不能为空") String imgUrl, Volunteer volunteer) {
        try {
            List<SearchFaceResponse.Data.MatchListItem.FaceItemsItem> faceItemsItems = aliYunService.searchFace(imgUrl, 1);
            SearchFaceResponse.Data.MatchListItem.FaceItemsItem faceItemsItem = faceItemsItems.get(0);
            if (faceItemsItem == null) {
                return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue(), null);
            }
            String oldManIdString = faceItemsItem.getEntityId();
            Integer oldManId = Integer.valueOf(oldManIdString.split("_")[1]);
            OldMan oldMan = oldManMapper.getById(oldManId);
            if (oldMan != null) {
                oldMan.setCases(caseMapper.getAllCaseByOldManId(oldManId));
            }
            System.out.println(faceItemsItem);
            Face face = new Face(imgUrl, new Timestamp(new Date().getTime()), faceItemsItem.getScore(), volunteer.getId(), oldManId, oldMan, (short) 1);
            if (face.getResult() >= 0.6) {
                if(face.getResult()<0.7){
                    face.setResult((float) (face.getResult()+0.2));
                }else if(face.getResult()<0.8){
                    face.setResult((float) (face.getResult()+0.1));
                }
                face.setState((short) 2);
                faceMapper.insertFace(face);
                rabbitTemplate.convertAndSend(RabbitMq.CASE_EXCHANGE.getValue(), RabbitMq.FACE_SUCCESS.getValue(), face);
            } else {
                face.setOldMan(null);
                face.setOldManId(null);
                faceMapper.insertFace(face);
            }
            return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue(), face);
        } catch (ClientException e) {
            e.printStackTrace();
            return new ResponseData<>(ResponseState.ERROR.getMessage(), ResponseState.ERROR.getValue());
        }
    }

    /**
     * 查询人脸识别记录
     */
    @Override
    public ResponseData<List<Face>> getFaceRecords(Integer oldManId) {
        List<Face> faces = faceMapper.getFaces(oldManId);
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue(), faces);
    }

    /**
     * 确认人脸识别结果
     */
    @Override
    @Transactional
    public ResponseData<Object> confirmResult(Integer faceId, Short state, Family family) {
        if (state != 3 && state != 4) {
            return new ResponseData<>("state只能是3或4", ResponseState.PARAM_IS_ERROR.getValue());
        }
        //判断是否重复操作
        Face face = faceMapper.getFaceById(faceId);
        if (face.getState() == 3 || face.getState() == 4) {
            return new ResponseData<>(ResponseState.OPERATION_HAI_FINISH.getMessage(), ResponseState.OPERATION_HAI_FINISH.getValue());
        }
        OldMan oldMan = oldManMapper.getOldManByFaceId(faceId);
        //判断该老人是否为该家属
        if (!family.getId().equals(oldMan.getFamilyId())) {
            return new ResponseData<>("该家属对此案件无操作权限", ResponseState.WITHOUT_PERMISSION.getValue());
        }
        faceMapper.updateState(faceId, state);
        if (state == 3) {
            List<Case> cases = caseMapper.getAllCaseByOldManId(oldMan.getId());
            for (Case nowCase : cases) {
                caseMapper.changeCaseState(nowCase.getId(), 2);
                nowCase.setState((short) 2);
                //设置完成时间
                nowCase.setEndTime(new Timestamp(new Date().getTime()));
                caseMapper.setEndTime(nowCase);
                System.out.println("人脸识别成功!");
                rabbitTemplate.convertAndSend(RabbitMq.CASE_EXCHANGE.getValue(), RabbitMq.CASE_FINISH.getValue(), nowCase);
//                rabbitTemplate.convertAndSend(RabbitMq.CASE_EXCHANGE.getValue(),RabbitMq.CASE_END.getValue(),nowCase);
            }
        }
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue());
    }

    /**
     * 第三方应用进行人脸识别
     */
    @Override
    public ResponseData<Face> clientFaceIdentification(String imgUrl, String appId,String accessKey) {
        Client rightClient = clientMapper.getByAppId(appId);
        if (rightClient == null) {
            return new ResponseData<>(ResponseState.USER_NOT_EXIST.getMessage(), ResponseState.USER_NOT_EXIST.getValue());
        }
        if (!rightClient.getAccessKey().equals(accessKey)) {
            return new ResponseData<>(ResponseState.APP_KEY_ERROR.getMessage(), ResponseState.APP_KEY_ERROR.getValue());
        }
        try {
            List<SearchFaceResponse.Data.MatchListItem.FaceItemsItem> faceItemsItems = aliYunService.searchFace(imgUrl, 1);
            SearchFaceResponse.Data.MatchListItem.FaceItemsItem faceItemsItem = faceItemsItems.get(0);
            if (faceItemsItem == null) {
                return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue(), null);
            }
            String oldManIdString = faceItemsItem.getEntityId();
            Integer oldManId = Integer.valueOf(oldManIdString.split("_")[1]);
            OldMan oldMan = oldManMapper.getById(oldManId);
            if (oldMan != null) {
                oldMan.setCases(caseMapper.getAllCaseByOldManId(oldManId));
            }
            Face face = new Face(imgUrl, new Timestamp(new Date().getTime()), faceItemsItem.getScore(), null, oldManId, oldMan, (short) 1);
            if (face.getResult() >= 0.8) {
                face.setState((short) 2);
            }
            return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue(), face);
        } catch (ClientException e) {
            e.printStackTrace();
            return new ResponseData<>(ResponseState.ERROR.getMessage(), ResponseState.ERROR.getValue());
        }
    }

    /**
     * 管理员查询人脸识别记录
     */
    @Override
    @Transactional
    public ResponseData<Page<Face>> adminGetFaces(Face face) {
        Integer sum = faceMapper.getAccordFaceSum(face);
        if (face.getPageNo() == null || face.getPageSize() == null) {
            face.setPageNo(1);
            face.setPageSize(sum);
        }
        face.setStartSize((face.getPageNo() - 1) * face.getPageSize());
        List<Face> faces = faceMapper.getAccordFace(face);
        for (Face faceItem : faces) {
            if (faceItem.getOldManId() != null) {
                faceItem.setOldMan(oldManMapper.getById(faceItem.getOldManId()));
                if (faceItem.getOldMan() != null) {
                    faceItem.getOldMan().setCases(caseMapper.getAllCaseByOldManId(faceItem.getOldManId()));
                }
            }
        }
        int pageNum;
        if (face.getPageSize() == 0) {
            pageNum = 0;
        } else {
            pageNum = sum / face.getPageSize();
            if (sum % face.getPageSize() > 0) {
                pageNum++;
            }
        }
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue(), new Page<>(face.getPageNo(), face.getPageSize(), pageNum, sum, faces));

    }

    /**
     * 管理员确认人脸识别结果
     */
    @Override
    public ResponseData<Object> adminConfirmResult(Integer faceId, short state) {
        if (state != 3 && state != 4) {
            return new ResponseData<>("state只能是3或4", ResponseState.PARAM_IS_ERROR.getValue());
        }
        //判断是否重复操作
        Face face = faceMapper.getFaceById(faceId);
        if (face.getState() == 3 || face.getState() == 4) {
            return new ResponseData<>(ResponseState.OPERATION_HAI_FINISH.getMessage(), ResponseState.OPERATION_HAI_FINISH.getValue());
        }
        OldMan oldMan = oldManMapper.getOldManByFaceId(faceId);
        faceMapper.updateState(faceId, state);
        if (state == 3) {
            List<Case> cases = caseMapper.getAllCaseByOldManId(oldMan.getId());
            for (Case nowCase : cases) {
                caseMapper.changeCaseState(nowCase.getId(), 2);
                nowCase.setState((short) 2);
                //设置完成时间
                nowCase.setEndTime(new Timestamp(new Date().getTime()));
                caseMapper.setEndTime(nowCase);
                System.out.println("人脸识别成功!");
                rabbitTemplate.convertAndSend(RabbitMq.CASE_EXCHANGE.getValue(), RabbitMq.CASE_FINISH.getValue(), nowCase);
//                rabbitTemplate.convertAndSend(RabbitMq.CASE_EXCHANGE.getValue(),RabbitMq.CASE_END.getValue(),nowCase);
            }
        }
        return new ResponseData<>(ResponseState.SUCCESS.getMessage(), ResponseState.SUCCESS.getValue());

    }


}
